<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use App\Model\ErrorLog;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Throwable;

class AppExceptionHandler extends ExceptionHandler
{
    /**
     * Undocumented variable
     *
     * @var LoggerInterface
     */
    protected $logger;

    /**
     *
     * @var RequestInterface
     */
    protected $request;

    protected $logRoute = [
        '/message/v1_4_0/chat/info',
    ];

    public function __construct()
    {
        // $this->logger=$logger;
        $this->logger = \Hyperf\Utils\ApplicationContext::getContainer()->get(\Hyperf\Logger\LoggerFactory::class)->get();
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $this->logger->error(sprintf('%s [%s行] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        // $this->logger->error($throwable->getTraceAsString());
        // return $response->withHeader("Server", "Hyperf")->withStatus(500)->withBody(new SwooleStream('Internal Server Error.'));
//
//        $this->request->fullUrl();
//
//        $this->request->all();
//
//        $this->request->getHeaders();

//        try {
//            // 报错日志
//            $path = $this->request->getPathInfo();
//            if (in_array($path, $this->logRoute)) {
//                $params = $this->request->all();
//
//                $header =  $this->request->getHeaders();
//
//                ErrorLog::addLog('message', 190, 'file', $path, $params, $header);
//            }
//        } catch (\Exception $e) {
//            $this->logger->error(sprintf('%s [%s行] in %s', $e->getMessage(), $e->getLine(), $e->getFile()));
//        }

        if (!env('APP_DEBUG')) {
            $result = [
                'ret' => -1,
                'result' => 500,
                'res_info' => '服务器出错了',
            ];

            // 阻止异常冒泡
            $this->stopPropagation();
            return $response->withHeader("Content-Type", "application/json")
                ->withStatus(500)
                ->withBody(new SwooleStream(json_encode($result, JSON_UNESCAPED_UNICODE)));
        } else {
            return $response;
        }
    }

    public function isValid(Throwable $throwable): bool
    {
        // log_info($throwable->getMessage());
        return true;
    }
}
